import { Button, Form, Input, InputNumber, Modal, Switch, Upload, message } from 'antd';
import ImgCrop from 'antd-img-crop';
import TextArea from 'antd/lib/input/TextArea';
import { useEffect, useState } from 'react';
import 'react-quill/dist/quill.snow.css';
import { PlusOutlined } from '@ant-design/icons';
import {
  addCategory,
  modifyCategory,
  type categoryParams,
} from '@/services/ant-design-pro/category';

type ModalsParams = {
  type?: number;
  title: string;
  isModalOpen: boolean;
  setIsModalOpen: (value: boolean) => void;
  // categoryList: category[];
  initialValues?: Data;
  fetchGetCategoryList: () => void;
};

export interface Data {
  channelLogo: string;
  channelName: string;
  description: string;
  id: number;
  ordered: number;
  status: number;
  [property: string]: any;
}

const Modals: React.FC<ModalsParams> = ({
  type = 0,
  title,
  isModalOpen,
  setIsModalOpen,
  initialValues,
  fetchGetCategoryList,
}) => {
  const [messageApi, contextHolder] = message.useMessage();
  const [form] = Form.useForm();
  const [fileList, setFileList] = useState<any[]>([]); //封面图片上传列表，封面只有一张图片，所以是数组项的第一项

  const onChangeChannelLogo = ({ fileList: newFileList }) => {
    setFileList(newFileList);
    // console.log('正在上传中');
    // console.log('value', newFileList);
  };

  const handleSubmit = async (values: categoryParams) => {
    const params = {
      ...values,
      channelLogo: fileList[0]?.response
        ? fileList[0]?.response?.data?.url
        : fileList[0]
        ? fileList[0].url
        : undefined,
      status: values.status ? 0 : 1,
    };

    // console.log('params', params);
    const res = await (type === 0
      ? addCategory(params)
      : modifyCategory({ ...params, id: initialValues?.id }));
    if (res.code === 0) {
      messageApi.success(type === 0 ? '分类添加成功' : '分类修改成功');
      fetchGetCategoryList();
      form.resetFields();
    } else {
      messageApi.error(res.msg);
    }

    setIsModalOpen(false);
  };

  useEffect(() => {
    if (initialValues) {
      form.setFieldsValue({ ...initialValues, status: initialValues.status ? false : true });

      setFileList([{ url: initialValues.channelLogo }]);
      // console.log([initialValues.coverUrl]);

      // setFileList([initialValues.coverUrl]);
    }
  }, [form, initialValues]);
  return (
    <>
      {contextHolder}
      <Modal
        title={title}
        open={isModalOpen}
        footer={null}
        onOk={() => setIsModalOpen(false)}
        onCancel={() => setIsModalOpen(false)}
      >
        <Form form={form} onFinish={handleSubmit} autoComplete="off">
          <Form.Item<categoryParams>
            name="channelName"
            label="分类名称"
            rules={[{ required: true, message: '请输入分类名称' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item<categoryParams> name="channelLogo" label="分类logo">
            <ImgCrop rotationSlider>
              <Upload
                action="http://114.132.98.212:10010/admin/api/v1/common/upload"
                listType="picture-card"
                fileList={fileList}
                onChange={onChangeChannelLogo}
                maxCount={1}
                data={{ type: '3' }}
                headers={{ token: localStorage.getItem('token') }}
              >
                <PlusOutlined />
              </Upload>
            </ImgCrop>
          </Form.Item>

          <Form.Item<categoryParams>
            name="ordered"
            label="分类排序"
            rules={[{ required: true, message: '请输入分类排序' }]}
          >
            <InputNumber min={0} max={1000} />
          </Form.Item>
          <Form.Item label="是否显示" name="status" valuePropName="checked">
            <Switch />
          </Form.Item>
          <Form.Item<categoryParams>
            name="description"
            label="分类描述"
            //rules={[{ required: true, message: '请输入分类描述' }]}
          >
            <TextArea autoSize={{ minRows: 6, maxRows: 8 }} />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 8, span: 16 }} style={{ marginRight: '-750px' }}>
            <Button type="primary" htmlType="submit">
              确认
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default Modals;
